package org.hum.scaffold.other;

import java.lang.reflect.Field;

public class 替换jvm虚拟机默认classloader {

	/**
	 * 方法1：启动命令VM增加参数：
	 * java -Djava.system.class.loader=myClassLoader myApplication
	 */
	public static void main(String[] args) throws Exception {
		/**
		 * 方法2：代码设置
		 */
		Field scl = ClassLoader.class.getDeclaredField("scl"); // Get system class loader
		scl.setAccessible(true); // Set accessible
		scl.set(null, new MyClassLoader(ClassLoader.class.getClassLoader())); // Update it to your class loader
		System.out.println("系统默认ClassLoader : " + ClassLoader.getSystemClassLoader());
	}
}

class MyClassLoader extends ClassLoader {
	
	public MyClassLoader(ClassLoader cl) {
		super(cl);
		System.out.println("MyClassLoader init");
	}

	@Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
		System.out.println("load class " + name);
		if ("org.hum.test.B".equals(name)) {
			System.out.println("c replace b...");
			return null; // XXX 替换成其他的
		}
		return super.loadClass(name, resolve);
    }
}

